package src.string;

public class no541 {
    // 字符串每段为2k，翻转每段的前k个字符
    public static void main(String[] args) {
        String s = "abc123456qw";
        int k = 3;
        System.out.println(reverseStr(s, k));

    }

    public static String reverseStr(String s, int k) {
        char[] charArray = s.toCharArray();
        // 每隔 2k 个字符的前 k 个字符进行反转，通过i += 2 * k控制每轮 i 的位置
        for (int i = 0; i < charArray.length; i = i + 2 * k) {
            if (i + k <= charArray.length) {
                reverseString(charArray, i, i + k - 1);  //剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符
                continue;
            }
            reverseString(charArray, i, charArray.length - 1);  //剩余字符少于 k 个，则将剩余字符全部反转
        }
        return new String(charArray);

    }

    public static void reverseString(char[] s, int i, int j) {
        while (i < j) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }
    }

}
